import { dictionaryGroupType, dictionaryType } from '@/types/project'
import { storeToRefs } from 'pinia'
import { projectStore } from '../modules/project'

/**
 * todo:添加一个字典信息
 *  */
export const addDictionary = (word: dictionaryType, parent: dictionaryGroupType) => {
    parent.children.push(word)
}
/**
 * todo:获取字典列表
 *  */
export const getDictionaryList = () => {
    var store = storeToRefs(projectStore())
    return store.dictionary
}

/**
 * todo:删除字典中的一个单元
 * parentId:父元素ID
 *  */
export const deleteWord = (id: string, parentId: string) => {
    var store = storeToRefs(projectStore())
    store.dictionary.value = store.dictionary.value.filter(item => {
        if (item.id == parentId) {
            item.children = item.children.filter(e => {
                if (e.id !== id) {
                    return e
                }
            })
        }
        return item
    })
}
/* 添加组，存在就更新，不存在就添加 */
export const addGroup = (group: dictionaryGroupType) => {
    var store = storeToRefs(projectStore())
    var index = store.dictionary.value.findIndex(item => {
        if (item.id === group.id) {
            return item
        }
    })
    if (index >= 0) {
        store.dictionary.value = store.dictionary.value.filter(item => {
            if (item.id === group.id) {
                item = group
            }
            return item
        })
    } else {
        store.dictionary.value.push(group)
    }

}

export const getGroupList = () => {
    var store = storeToRefs(projectStore())
    return store.dictionary
}


/**
 * todo:删除本地记录
 *  */
export const clearGroup = () => {
    var store = storeToRefs(projectStore())
    store.dictionary.value = []
}


export const deleteGroup = (id: string) => {
    var store = storeToRefs(projectStore())
    store.dictionary.value = store.dictionary.value.filter(e => {
        return e.id !== id
    })
}

/**
 * todo:将kv数组转成下拉框的数组
 *  */
export const toOptions= (array:Array<dictionaryType>) => {
    return array.map(item=>{
        return {
            label:item.key,
            value:item.value,
        }
    })
}